package com.loong.musicdemo.ui.mine.recent;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.loong.musicdemo.R;
import com.loong.musicdemo.model.Comment;
import com.loong.musicdemo.ui.mine.adapter.MineCommentAdapter;
import com.loong.musicdemo.util.FormatTimeUtil;
import com.loong.musicdemo.util.dataDeal.MvDeal;

import java.util.List;

public class PlayMvActivity extends AppCompatActivity implements SurfaceHolder.Callback, View.OnClickListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
    private ImageView playOrPauseIv;
    private SurfaceView mvSurfaceView;
    private MediaPlayer mPlayer;
    private SeekBar mSeekBar;
    private RelativeLayout mvRoot;
    private LinearLayout mvControl;
    private RecyclerView mv_comments_view;
    private TextView startTime, endTime;
    private ImageView forwardButton, backwardButton;
    private Toolbar toolbar;
    private TextView playCount;
    private ProgressBar progressBar;
    private boolean isShow = false;
    public static final int UPDATE_TIME = 0x0001;
    public static final int HIDE_CONTROL = 0x0002;
    String mvUrl = "";
    String mvId = "";
    String mvName = "";
    String mvPlayCount = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        setContentView(R.layout.activity_play_mv);
        initMvData();
        initView();
        initSurfaceView();
        initPlayer();
        initEvent();
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(mvName);
            actionBar.setDisplayHomeAsUpEnabled(true);//若工具栏可用,则显示Home菜单
        }
        new MvCommentTask().execute();
    }


    /**
     * 播放mv消息处理机制
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE_TIME:
                    updateTime();
                    mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 500);
                    break;
                case HIDE_CONTROL:
                    hideControl();
                    break;
            }
        }
    };

    private void initMvData(){
        mvUrl = getIntent().getStringExtra("mvUrl");
        mvId = getIntent().getStringExtra("mvId");
        mvName = getIntent().getStringExtra("mvName");
        mvPlayCount = getIntent().getStringExtra("mvPlayCount");
    }

    private void initEvent(){
        playOrPauseIv.setOnClickListener(this);
        mvRoot.setOnClickListener(this);
        forwardButton.setOnClickListener(this);
        backwardButton.setOnClickListener(this);
        mSeekBar.setOnSeekBarChangeListener(this);
    }

    private void initSurfaceView(){
        mvSurfaceView = findViewById(R.id.surfaceView);
        mvSurfaceView.setZOrderOnTop(false);
        mvSurfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mvSurfaceView.getHolder().addCallback(this);
    }
    private void initPlayer() {
        mPlayer = new MediaPlayer();
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnErrorListener(this);
        try {
            mPlayer.setDataSource(mvUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initView(){
        playOrPauseIv = findViewById(R.id.playOrPause);
        mSeekBar = findViewById(R.id.tv_progess);
        mvRoot = findViewById(R.id.mv_root);
        mvControl = findViewById(R.id.mv_control);
        mv_comments_view = findViewById(R.id.mv_comments_view);
        startTime = findViewById(R.id.tv_start_time);
        endTime = findViewById(R.id.tv_end_time);
        forwardButton = findViewById(R.id.fast_forward);
        backwardButton = findViewById(R.id.fast_back);
        progressBar = findViewById(R.id.progress_bar);
        toolbar = findViewById(R.id.toolbar);
        playCount = findViewById(R.id.play_count);
        playCount.setText("播放次数:"+mvPlayCount);
    }
    /**
     * 设置返回菜单
     *
     * @param item 菜单项
     * @return 是否触发
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home){
            mPlayer.pause();
            mPlayer.release();
            mPlayer = null;
            this.finish();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPlayer.pause();
        mPlayer.release();
        mPlayer = null;
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mPlayer.setDisplay(holder);
        mPlayer.prepareAsync();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fast_back:
                backWard();
                break;
            case R.id.fast_forward:
                forWard();
                break;
            case R.id.playOrPause:
                play();
                break;
            case R.id.mv_root:
                showControl();
                break;
        }
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if(mPlayer != null && fromUser){
            mPlayer.seekTo(progress);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        startTime.setText(FormatTimeUtil.formatTimeToStr(mp.getCurrentPosition()));
        endTime.setText(FormatTimeUtil.formatTimeToStr(mp.getDuration()));
        mSeekBar.setMax(mp.getDuration());
        mSeekBar.setProgress(mp.getCurrentPosition());
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        return false;
    }
    private void play() {
        if (mPlayer == null) {
            return;
        }
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
            mHandler.removeMessages(UPDATE_TIME);
            mHandler.removeMessages(HIDE_CONTROL);
            playOrPauseIv.setVisibility(View.VISIBLE);
            playOrPauseIv.setImageResource(android.R.drawable.ic_media_play);
        } else {
            mPlayer.start();
            mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 500);
            mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
            playOrPauseIv.setVisibility(View.INVISIBLE);
            playOrPauseIv.setImageResource(android.R.drawable.ic_media_pause);
        }
    }

    /**
     * 设置快进10秒方法
     */
    private void forWard(){
        if(mPlayer != null){
            int position = mPlayer.getCurrentPosition();
            mPlayer.seekTo(position + 10000);
        }
    }

    /**
     * 设置快退10秒的方法
     */
    public void backWard(){
        if(mPlayer != null){
            int position = mPlayer.getCurrentPosition();
            if(position > 10000){
                position-=10000;
            }else{
                position = 0;
            }
            mPlayer.seekTo(position);
        }
    }
    private void hideControl() {
        isShow = false;
        mHandler.removeMessages(UPDATE_TIME);
        mvControl.animate().setDuration(300).translationY(mvControl.getHeight());
    }

    private void updateTime() {
        if(mPlayer!=null){
            startTime.setText(FormatTimeUtil.formatTimeToStr(mPlayer.getCurrentPosition()));
            mSeekBar.setProgress(mPlayer.getCurrentPosition());
        }
    }
    private void showControl() {
        if (isShow) {
            play();
        }
        isShow = true;
        mHandler.removeMessages(HIDE_CONTROL);
        mHandler.sendEmptyMessage(UPDATE_TIME);
        mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
        mvControl.animate().setDuration(300).translationY(0);
    }

    class MvCommentTask extends AsyncTask<Comment,Void, List<Comment>>{
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(List<Comment> comments) {
            super.onPostExecute(comments);
            Log.i("mvComments", comments.size()+"");
            LinearLayoutManager manager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
            MineCommentAdapter adapter = new MineCommentAdapter(comments,getApplicationContext());
            mv_comments_view.setLayoutManager(manager);
            mv_comments_view.setAdapter(adapter);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        protected List<Comment> doInBackground(Comment... comments) {
            List<Comment> list = MvDeal.getMvHotCommentsByMvId(mvId);
            return list;
        }
    }

}
